package com.cc.ttsreader

import android.content.Context
import android.os.AsyncTask
import android.os.Build
import android.speech.tts.TextToSpeech
import android.util.Log
import android.widget.Toast
import kotlinx.coroutines.*
import java.util.*

private const val TAG = "TextToSpeechHelper"

class TextToSpeechHelper(var context: Context, var initCallBack: (isSupport: Boolean) -> Unit) :
    TextToSpeech.OnInitListener {
    private val tts = TextToSpeech(context, this)
    var isSupport = false
    override fun onInit(status: Int) {
        if (status == TextToSpeech.SUCCESS) {
            val result2 = tts.setLanguage(Locale.CHINESE);
            if (result2 == TextToSpeech.LANG_MISSING_DATA
                || result2 == TextToSpeech.LANG_NOT_SUPPORTED
            ) {
                Log.e(TAG, "不支持的语言")
                isSupport = false
            } else {
                isSupport = true
            }
        }
        initCallBack.invoke(isSupport)
    }

    fun speech(charSequence: CharSequence, completeListener: () -> Unit) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            tts.speak(charSequence, TextToSpeech.QUEUE_FLUSH, null, "")
        }
        GlobalScope.launch {
            while (tts.isSpeaking) {
                delay(20)
            }
            withContext(Dispatchers.Main) {
                completeListener.invoke()
            }
        }
    }
}